<template>
  <div>
    <div class="con">
      <el-input
        class="el-input"
        placeholder="请输入要查询的用户"
        prefix-icon="el-icon-search"
        v-model="msg"
        clearable
      ></el-input>
      <el-button type="primary" @click="addUser" class="bnt1">添加管理员</el-button>
    </div>
    <br />
    <!-- 添加管理员 -->
    <el-dialog
      class="dialog"
      title="添加管理员"
      :visible.sync="dialogFormVisible"
      :show-close="false"
      :before-close="addUser"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="管理员账号" prop="account">
          <el-input v-model="ruleForm.account"></el-input>
        </el-form-item>
        <el-form-item label="管理员名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="ruleForm.role" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="escButton()">取消</el-button>
        <el-button @click="addSuccess()" type="primary">添加</el-button>
      </div>
    </el-dialog>
    <el-table :data="currList" style="width: 100%" border>
      <el-table-column prop="administrators_id" label="管理员id"></el-table-column>
      <el-table-column prop="administrators_account" label="管理员账号"></el-table-column>
      <el-table-column prop="administrators_name" label="管理员名称"></el-table-column>
      <el-table-column prop="role" label="角色名称">
        <template slot-scope="scope">
          <span>{{scope.row.role.role_name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="administrators_founder_name" label="创建人"></el-table-column>
      <el-table-column prop="administrators_founder_date" label="创建时间"></el-table-column>
      <el-table-column prop="last_login_date" label="登录时间"></el-table-column>
      <el-table-column prop="last_login_ip" label="登录ip"></el-table-column>
      <el-table-column prop="administrators_state" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.administrators_state === 0 ? '启用' : '禁用'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <!-- 分页器 -->
    <el-pagination
      @current-change="changePage"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      background
      v-show="showPage"
      layout="prev, pager, next, jumper"
      :total="list.length"
    ></el-pagination>
    <!-- 修改信息 -->
    <el-dialog
      class="dialog"
      title="修改信息"
      :visible.sync="show"
      :show-close="false"
      :before-close="handleEdit"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="管理员名称" prop="changName">
          <el-input v-model="ruleForm.changName"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="changeRole">
          <el-select v-model="ruleForm.changeRole" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="changePwd">
          <el-input v-model="ruleForm.changePwd"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="ruleForm.status" label="0">启用</el-radio>
          <el-radio v-model="ruleForm.status" label="1">禁用</el-radio>
        </el-form-item>
        <el-form-item label="备注" prop="changeRemark">
          <el-input v-model="ruleForm.changeRemark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="escChange()">取消</el-button>
        <el-button @click="changeSuccess()" type="primary">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import http from '../api/index';
export default {
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入管理员名称'));
      } else {
        var res = /^[a-zA-Z_\W]*[0-9a-zA-Z]+$/;
        if (value.length < 2 || value.length > 6 || !res.test(value)) {
          callback(new Error('长度2-6，不能是特殊字符'));
        } else {
          callback();
        }
      }
    };
    var validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账户'));
      } else {
        var res = /^[a-zA-Z_\W]*[0-9a-zA-Z]+$/;
        if (value.length < 8 || value.length > 16 || !res.test(value)) {
          callback(new Error('长度8-16，不能是特殊字符'));
        } else {
          callback();
        }
      }
    };
    var validatePwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        var res = /^[a-zA-Z_\W]*[0-9a-zA-Z]+$/;
        if (value.length < 6 || value.length > 16 || !res.test(value)) {
          callback(new Error('长度6-16，不能是特殊字符'));
        } else {
          callback();
        }
      }
    };
    return {
      msg: '',
      list: [], //总数据
      currList: [], //当前展示的数据数据
      currPage: 1, //当前页 1
      pageSize: 5, //每页的数据条数 6
      number: 0, // 下标
      currentPage: 1,
      dialogFormVisible: false,
      show: false,
      showPage: true,
      formLabelWidth: '120px',
      id: '',
      roleId:'',
      token:sessionStorage.getItem('token'),
      options: [
        {
          value: '1',
          label: '超级管理员',
        },
        {
          value: '2',
          label: '软件管理员',
        },
        {
          value: '3',
          label: '用户管理员',
        },
        {
          value: '4',
          label: '论坛管理员',
        },
      ],
      ruleForm: {
        account: '',
        name: '',
        role: '',
        password: '',
        status: '',
        remark: '',
        changName: '',
        changePwd: '',
        changeRemark: '',
        changeRole: '',
      },
      rules: {
        account: [
          { required: true, validator: validateAccount, trigger: 'blur' },
        ],
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        role: [
          { required: true, message: '请选择管理员角色', trigger: 'blur' },
          // { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' },
        ],
        password: [{ required: true, validator: validatePwd, trigger: 'blur' }],
      },
    };
  },
  // 获取数据
  mounted() {
    http.mangerPage().then((res) => {
      console.log(res);
      this.list = res;
      console.log(this.list);
      this.setList(1);
    });
  },
  methods: {
    // 分页
    setList(index) {
      this.currList = this.list.slice(
        (index - 1) * this.pageSize,
        index * this.pageSize
      );
    },
    changePage(val) {
      // console.log(val); //分页器的页码变化事件中
      this.currPage = val; //val时当前页码，页码改变时，直接赋值给当前页
      this.setList(val); //分页
    },
    // 修改按钮
    handleEdit(i, row) {
      console.log(i, row);
      console.log(row.role.role_id);
      console.log(row.role.role_name);
      this.id = row.administrators_id;
      this.roleId=row.role.role_id;
      this.ruleForm.changName = row.administrators_name;
      this.ruleForm.status = row.administrators_state + '';
      this.ruleForm.changeRole = row.role.role_id;
      this.ruleForm.role = row.role.role_id;
      if(row.role.role_id===1){
        this.ruleForm.changeRole = row.role.role_name;
      }else if(row.role.role_id===2){
        this.ruleForm.changeRole = row.role.role_name;
      }else if(row.role.role_id===3){
        this.ruleForm.changeRole = row.role.role_name;
      }else if(row.role.role_id===4){
        this.ruleForm.changeRole = row.role.role_name;
      }
      // console.log(this.ruleForm.status);
      // console.log(this.ruleForm.changName);
      // console.log(this.id);
      // console.log(this.options[(this.id)-1].value);
      this.show = true;
    },
    // 添加按钮
    addUser() {
      console.log(this.token);
      this.dialogFormVisible = true;
    },
    // 修改成功
    changeSuccess() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          http.updateManage( {
              administrators_id: this.id,
              administrators_name: this.ruleForm.changName,
              role: {
                role_id: this.roleId,
              },
              administrators_password: this.ruleForm.changePwd,
              administrators_state: this.ruleForm.status,
              remarks: this.ruleForm.changeRemark,
            })
            .then((res) => {
              console.log(res);
            });
          console.log(this.ruleForm.changName);
          console.log(this.ruleForm.changeRole);

          console.log(this.ruleForm.status);
          this.show = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加用户成功
    addSuccess() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          http.addManage({
              tokenAdministrators:this.token,
              administrators_account: this.ruleForm.account,
              administrators_name: this.ruleForm.name,
              role: {
                role_id: this.ruleForm.role,
              },
              administrators_password: this.ruleForm.password,
              remarks: this.ruleForm.remark,
            })
            .then((res) => {
              console.log(res);
            });
          console.log(this.ruleForm.account);
          console.log(this.ruleForm.role);
          this.ruleForm.account = '';
          this.ruleForm.role = '';
          this.ruleForm.name = '';
          (this.ruleForm.password = ''), (this.ruleForm.remark = '');
          this.dialogFormVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 取消添加
    escButton() {
      this.$refs.ruleForm.resetFields();
      this.dialogFormVisible = false;
    },
    // 取消修改
    escChange() {
      this.$refs.ruleForm.resetFields();
      this.show = false;
    },
  },
  watch: {
    //   筛选
    msg(val) {
      console.log(val);
      this.showPage = false;
      let arr = [];
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].administrators_name.indexOf(val) !== -1) {
          arr.push({
            administrators_id: this.list[i].administrators_id,
            administrators_account: this.list[i].administrators_account,
            administrators_name: this.list[i].administrators_name,
            role: { role_name: this.list[i].role.role_name },
            administrators_founder_id: this.list[i].administrators_founder_id,
            administrators_founder_date: this.list[i]
              .administrators_founder_date,
            last_login_date: this.list[i].last_login_date,
            last_login_ip: this.list[i].last_login_ip,
            administrators_state: this.list[i].administrators_state,
            remarks: this.list[i].remarks,
          });
        }
      }
      console.log(arr);
      this.currList = JSON.parse(JSON.stringify(arr));
      if (val === '') {
        // 让分页器出现
        this.showPage = true;
        this.setList(this.currPage);
      }
    },
  },
};
</script>
<style scoped>
/* .con {
  margin-left: 86px;
} */
.el-input {
  width: 400px;
}
.bnt1 {
  margin-left: 98px;
}
</style>